package com.qsj.easydarwin.controller;

import com.alibaba.excel.EasyExcel;
import com.qsj.easydarwin.pojo.SaveVideoAnalysisVO;
import com.qsj.easydarwin.pojo.VideoAnalysis;
import com.qsj.easydarwin.service.impl.VideoAnalysisService;
import com.qsj.easydarwin.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Q1sj
 * @version 1.0
 * @date 2020/7/7 14:51
 */
@RequestMapping("/videoAnalysis")
@Controller
public class VideoAnalysisController {
    @Autowired
    private VideoAnalysisService videoAnalysisService;


    /**
     * 保存视频分析数据
     *
     * @param request
     * @return
     */
    @PostMapping("/save")
    public ResponseEntity<Boolean> save(@RequestBody SaveVideoAnalysisVO request) {
        // 删除历史数据
        int i = this.videoAnalysisService.deleteByVideoName(request.getVideoName());
        // 保存到数据库
        if (this.videoAnalysisService.insert(request)>0) {
            return ResponseEntity.ok(true);
        }else{
            return ResponseEntity.badRequest().body(false);
        }
    }

    @GetMapping("/get")
    public ResponseEntity<Response<SaveVideoAnalysisVO>> get(String videoName){
        SaveVideoAnalysisVO response = this.videoAnalysisService.getByVideoName(videoName);
        if (response !=null){
            return ResponseEntity.ok(new Response<>(true,response));
        }else {
            return ResponseEntity.ok(new Response<>(false,new SaveVideoAnalysisVO()));
        }
    }

    /**
     * 导出全部数据
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        List<VideoAnalysis> list = this.videoAnalysisService.selectAll();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(String.valueOf(System.currentTimeMillis()), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), VideoAnalysis.class).sheet("视频分析结果").doWrite(list);
    }
}
